package com.zhss.dfs.namenode.server;

import java.util.LinkedList;
import java.util.List;

/**
 * 负责管理内存中的文件目录树
 */
public class FSDirectory {
    /**
     * 内存中的文件目录树
     */
    private INodeDirectory  dirTree;

    public FSDirectory(){
        this.dirTree = new INodeDirectory("/");
    }

    public void mkdir(String path){
        // /usr/warehouse/hive
        //判断根目录下有没有usr目录
        //如果有，再判断usr下是否有warehouse，如果没有先创建warehouse
        //接着再对hive创建一个节点，挂载上去
        synchronized (dirTree){
            String[] paths = path.split("/");
            INodeDirectory parentDir = null;
            for (String splitedPath : paths) {
                if(splitedPath.trim().equals("")){
                    continue;
                }
                INodeDirectory dir = findDirectory(
                        parentDir == null ? dirTree : parentDir,splitedPath);
                if(dir != null){
                    parentDir = dir;
                    continue;
                }

                INodeDirectory child = new INodeDirectory(splitedPath);
                parentDir.addChild(child);
            }
        }
    }

    /**
     * 对文件目录树递归查找目录
     * @param dir
     * @param path
     * @return
     */
    private INodeDirectory findDirectory(INodeDirectory dir,String path){
        if(dir.getChildren().size() == 0){
            return  null;
        }
        INodeDirectory resultDir = null;
        for (INode child : dir.getChildren()) {
            if(child instanceof INodeDirectory){
                INodeDirectory childDir = (INodeDirectory)child;
                if(childDir.getPath().equals(path)){
                    return childDir;
                }
                resultDir = findDirectory((INodeDirectory) child,path);
                if(resultDir != null){
                    return resultDir;
                }
            }
        }
        return null;
    }

    /**
     * 文件目录树的一个节点
     */
    private interface INode{

    }

    /**
     * 文件目录树的一个目录
     */
    public static class INodeDirectory implements INode {
        private String path;
        private List<INode> children;

        public INodeDirectory(String path){
            this.path = path;
            this.children = new LinkedList<INode>();
        }
        public void addChild(INode node){
            children.add(node);
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public List<INode> getChildren() {
            return children;
        }

        public void setChildren(List<INode> children) {
            this.children = children;
        }
    }

    /**
     * 文件目录树的一个文件
     */
    public static class INodeFile implements INode {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
